package com.ysu.his.register.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ysu.his.constant.RedisConstant;
import com.ysu.his.entity.user.User;
import com.ysu.his.utils.AuthContextUtil;
import com.ysu.his.vo.common.Result;
import com.ysu.his.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginUserInterceptor implements HandlerInterceptor
{
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {

        //1.获取请求方式
        String method = request.getMethod();
        //请求方式是options，预检请求，直接放行
        if ("OPTIONS".equals(method))
        {
            return true;
        }

        //2.从请求头中获取token
        String token = request.getHeader("Authorization");
        //3.token为空 ，返回错误提示
        if (StrUtil.isEmpty(token))
        {
            responseNoLoginInfo(response);
            return false;
        }
        //4.用token查询redis查询用户信息
        String userInfoString=redisTemplate.opsForValue().get(RedisConstant.LOGIN_USER+token);
        //redis中没有用户信息，返回错误信息
        if (StrUtil.isEmpty(userInfoString))
        {
            responseNoLoginInfo(response);
            return false;
        }

        //5.将用户信息放入ThreadLocal中
        User user = JSON.parseObject(userInfoString, User.class);
        AuthContextUtil.set(user);

        //6.将redis中用户信息更新过期时间
        redisTemplate.expire(RedisConstant.LOGIN_USER +token,RedisConstant.USER_INFO_TTL, TimeUnit.MINUTES);
        //7.放行
        return true;
    }

    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex)
    {
        //移除threadLocal的数据
        AuthContextUtil.reomve();
    }
}
